import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/utils/utils.dart';
import 'package:vape_xe/values/values.dart';
import 'package:vape_xe/widgets/widgets.dart';

import 'exchange_child/view.dart';

class ExchangeDialogView extends StatefulWidget {
  final String? id1; // 烟杆/一次性的ID
  final String? id2; // 烟弹的ID
  final String modelNum;
  final int type; //0 烟杆 1.烟弹 2.一次性

  const ExchangeDialogView({
    super.key,
    required this.modelNum,
    required this.type,
    this.id1,
    this.id2,
  });

  @override
  _ExchangeDialogViewState createState() => _ExchangeDialogViewState();
}

class _ExchangeDialogViewState extends State<ExchangeDialogView> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _selectedIndex = 0; // 用于跟踪当前选中的Tab索引

  @override
  void initState() {
    super.initState();
    if (widget.type != 2) {
      _selectedIndex = widget.type;
      _tabController = TabController(initialIndex: widget.type, length: 2, vsync: this)
        ..addListener(() {
          setState(() {
            _selectedIndex = _tabController.index; // 更新选中的Tab索引
          });
        });
    }
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 800.h,
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: const BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20)),
        boxShadow: [Shadows.dialogShadow],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (widget.type != 2)
            TabBar(
              dividerHeight: 0,
              indicator: const UnderlineTabIndicator(
                borderSide: BorderSide.none,
                insets: EdgeInsets.zero,
              ),
              controller: _tabController,
              tabs: [
                Tab(icon: _getIcon('ic_yangan_', 0)),
                Tab(icon: _getIcon('ic_yandan_', 1)),
              ],
            ),
          16.hGap,
          GestureDetector(
            onTap: () async {
              var data = await Get.toNamed(Routes.SCAN);
              await Future.delayed(const Duration(milliseconds: 500));
              if (data != null) {
                String code = Uri.parse(data).queryParameters['c'] ?? '';
                if (code.isEmpty) return;
                Loading.show();
                Request().post('/userVape/scanQrcode', {
                  'code': code,
                }).then((result) {
                  Get.dialog(ScanDialogView(params: result['result']), barrierDismissible: false);
                });
              }
            },
            child: Container(
              width: double.infinity,
              margin: EdgeInsets.symmetric(horizontal: 16.w),
              height: 53.h,
              decoration: BoxDecoration(color: Colors.white10, borderRadius: 16.radius),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    'assets/images/ic_scan.webp',
                    width: 22.w,
                    height: 22.w,
                  ),
                  2.hGap,
                  Text(
                    'Add a new item by scanning the code'.tr,
                    style: TextStyle(fontSize: 11.sp),
                  )
                ],
              ),
            ),
          ),
          8.hGap,
          Expanded(
            child: widget.type != 2
                ? TabBarView(
                    controller: _tabController,
                    children: [
                      ExchangeListView(tag: '0', id: widget.id1, modelNum: widget.modelNum),
                      ExchangeListView(tag: '1', id: widget.id2, modelNum: widget.modelNum),
                    ],
                  )
                : ExchangeListView(tag: widget.type.toString(), id: widget.id1, modelNum: widget.modelNum),
          ),
          8.hGap,
          GestureDetector(
            onTap: () => Navigator.pop(context),
            child: Container(
              width: double.infinity,
              margin: EdgeInsets.symmetric(horizontal: 16.w),
              height: 53.h,
              decoration: BoxDecoration(color: Colors.white10, borderRadius: 16.radius),
              child: Center(
                child: Text(
                  'Cancel'.tr,
                  style: TextStyle(fontSize: 16.sp, fontFamily: 'Montserrat', fontWeight: FontWeight.bold),
                ),
              ),
            ),
          ),
          20.hGap,
        ],
      ),
    );
  }

  // 根据索引返回正确的图标
  Widget _getIcon(String name, int index) {
    return Image.asset(
      'assets/images/$name${index == _selectedIndex ? 'pre' : 'nor'}.webp',
      width: 24.w,
      height: 24.w,
    );
  }
}
